< previous page page_209 next page >

Page 209
Arrays of Structures
How is it possible for the function to return a correct result, yet the structure entry to remain empty? The answer is, it isn't. The only possibility is if the structure entry you are looking at is not the same one seen by the API function.
How can this be?
Think, for a moment, about how strings are stored within Visual Basic. They are always stored as Unicode strings. Does this apply also to strings inside of structures?
Yes.
So how can a structure be passed to an API function that expects an ANSI string?
Visual Basic must convert the structure from Unicode to ANSI. To do this, it creates a temporary copy of the structure with the strings converted into ANSI as shown in Figure S18-1.
0209-01.gif
Figure S18-1:
Passing structures in arrays to an API function
But what happens if you want to pass a pointer to an array of such structures? Normally you can pass a pointer to an array by passing a pointer to the first element in the array. But in this case Visual Basic passes a pointer to the temporary structure. Visual Basic does not convert all of the entries in the arraythere is no reason for it to do so because, as far as VB is concerned, you are only passing the first element to the API function.
Which raises the question, how could the previous solution have returned a correct result? Setting the dwSize parameter for each entry in the array shouldn't have made any difference if only one entry was actually passed.
Frankly, I don't know. Perhaps it's a fluke. Perhaps the memory immediately after the temporary structure just happens to hold leftover data from a previous call that contains the record size. In other words, there's every chance that it won't work in most casesespecially if there are more than two phone book entries.
So what now?
One solution is to explicitly copy the array of structures into a memory buffer.1
7017a6ead0e3c4111b47a554df321e9f.gif 7017a6ead0e3c4111b47a554df321e9f.gif
1 Another solution would be to change the szEntryName field of the RASENTRYNAME structure from a fixed-length string to a byte array. This eliminates the need for Visual Basic to create a temporary structure, but does require you to perform explicit ANSI-to-Unicode string conversions for the szEntryName field.

 
< previous page page_209 next page >